package com.zone.gateway.core.socket;

import com.zone.gateway.core.session.Configuration;
import com.zone.gateway.core.session.GatewaySessionFactory;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author: zongzi
 * @description: 会话服务器，基于netty实现server端，大部分是一套模板代码
 * @date: 2025/4/17
 */
public class SessionServer {

    private final Configuration configuration;
    private final GatewaySessionFactory gatewaySessionFactory;

    public SessionServer(GatewaySessionFactory gatewaySessionFactory, Configuration configuration) {
        this.configuration = configuration;
        this.gatewaySessionFactory = gatewaySessionFactory;
    }

    /**
     * 启动 netty server
     */
    public Channel bind() {
        // 底层线程模型，创建两个工作组
        final EventLoopGroup bossGroup = new NioEventLoopGroup(configuration.getBossNThreads());
        final EventLoopGroup workerGroup = new NioEventLoopGroup(configuration.getWorkerNThreads());

        // netty server 启动引导类
        ServerBootstrap serverBootstrap = new ServerBootstrap().group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new SessionChannelInitializer(gatewaySessionFactory, configuration));
        try {
            // 绑定端口(syncUninterruptibly() 阻塞等待异步操作完成, 关键操作必须完成的场景)
            ChannelFuture channelFuture = serverBootstrap.bind(configuration.getNettyServerPort()).syncUninterruptibly();
            // 获取通道关闭的异步通知，返回一个将在通道关闭时被通知的 ChannelFuture
//            channelFuture.channel().closeFuture().syncUninterruptibly();
            return channelFuture.channel();
        } finally {
//            bossGroup.shutdownGracefully();
//            workerGroup.shutdownGracefully();
        }
    }
}
